<template>
  <div class="user-management-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <!-- 用户名搜索 -->
      <input
        type="text"
        v-model="searchQuery"
        placeholder="输入用户名关键词"
        @keyup.enter="fetchUserData"
      />

      <!-- 日期选择 -->
      <span>创建时间段：</span>
      <input type="date" v-model="queryStartDate" class="date-input" />--
      <input type="date" v-model="queryEndDate" class="date-input" />

      <button class="search-btn" @click="fetchUserData">
        <i class="icon-search"></i> 搜索
      </button>
      <button
        class="reset-btn"
        @click="resetSearch"
        v-show="hasSearchCondition"
      >
        重置
      </button>
    </div>

    <!-- 加载状态 -->
    <div class="loading-state" v-if="isLoading">
      <p>加载中...</p>
    </div>

    <!-- 表格区域 -->
    <div class="user-table-container" v-else>
      <!-- 表格标题栏 -->
      <div class="table-header">
        <div class="table-cell id-column">ID</div>
        <div class="table-cell name-column">用户名</div>
        <div class="table-cell realname-column">真实姓名</div>
        <div class="table-cell gender-column">性别</div>
        <div class="table-cell type-column">用户类型</div>
        <div class="table-cell time-column">创建时间</div>
        <div class="table-cell action-column">操作</div>
      </div>

      <!-- 表格内容区 -->
      <div class="table-body">
        <!-- 数据为空时显示 -->
        <div class="empty-state" v-if="userList.length === 0">
          <p>
            {{ hasSearchCondition ? "没有找到匹配的用户" : "暂无用户数据" }}
          </p>
        </div>

        <!-- 数据列表 -->
        <div class="table-row" v-for="user in userList" :key="user.id">
          <div class="table-cell id-column">{{ user.id }}</div>
          <div class="table-cell name-column" readonly>
            {{ user.loginName }}
          </div>
          <div class="table-cell realname-column">{{ user.userName }}</div>
          <div class="table-cell gender-column">
            {{ getGenderText(user.sex) }}
          </div>
          <div class="table-cell type-column">
            {{ getUserTypeText(user.type) }}
          </div>
          <div class="table-cell time-column">
            {{ user.createTime }}
          </div>
          <div class="table-cell action-column">
            <button class="update-btn" @click="handleUpdate(user.id)">
              修改
            </button>
            <button
              class="delete-btn"
              @click="handleDelete(user.id)"
              :disabled="isDeleting"
            >
              删除
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-container" v-if="userList.length > 0 && !isLoading">
      <button
        class="page-btn"
        :disabled="currentPage === 1 || isLoading"
        @click="goToFirstPage"
      >
        首页
      </button>

      <button
        class="page-btn"
        :disabled="currentPage === 1 || isLoading"
        @click="goToPrevPage"
      >
        上一页
      </button>

      <span class="page-info"
        >第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span
      >
      <button
        class="page-btn"
        :disabled="currentPage === totalPages || isLoading"
        @click="goToNextPage"
      >
        下一页
      </button>
      <button
        class="page-btn"
        :disabled="currentPage === totalPages || isLoading"
        @click="goToLastPage"
      >
        末页
      </button>
      <select
        v-model="pageSize"
        @change="handlePageSizeChange"
        class="page-size-select"
        :disabled="isLoading"
      >
        <option value="10">每页10条</option>
        <option value="20">每页20条</option>
        <option value="30">每页30条</option>
      </select>
    </div>

    <!-- 修改用户表单 -->
    <div class="modal-overlay" v-if="showUserModal">
      <div class="user-modal">
        <div class="modal-header">
          <h3>修改用户</h3>
          <button class="close-btn" @click="closeUserModal">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="submitUserForm">
            <div class="form-group">
              <label for="user-loginName">用户名</label>
              <input
                type="text"
                id="user-loginName"
                v-model="userForm.loginName"
                required
                readonly
              />
              <span style="color: red">无法修改</span>
            </div>

            <div class="form-group">
              <label for="user-userName">真实姓名</label>
              <input
                type="text"
                id="user-userName"
                v-model="userForm.userName"
                required
              />
            </div>

            <div class="form-group">
              <label for="user-identityCode">身份证号</label>
              <input
                type="text"
                id="user-identityCode"
                v-model="userForm.identityCode"
                required
                readonly
              />
            </div>

            <div class="form-group">
              <label for="user-mobile">手机号</label>
              <input
                type="text"
                id="user-mobile"
                v-model="userForm.mobile"
                required
                readonly
              />
            </div>

            <div class="form-group">
              <label>性别</label>
              <div class="radio-group">
                <label>
                  <input
                    type="radio"
                    v-model="userForm.sex"
                    value="1"
                    required
                  />
                  男
                </label>
                <label>
                  <input type="radio" v-model="userForm.sex" value="0" /> 女
                </label>
              </div>
            </div>
            <div class="form-actions">
              <button type="button" class="cancel-btn" @click="closeUserModal">
                取消
              </button>
              <button type="submit" class="submit-btn" :disabled="isSubmitting">
                {{ isSubmitting ? "提交中..." : "确认" }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "UserList",
  data() {
    return {
      userList: [],
      searchQuery: "", // 用户名搜索条件
      queryStartDate: "", // 日期搜索条件:起始时间
      queryEndDate: "", // 日期搜索条件:结束时间
      currentPage: 1,
      pageSize: 10,
      totalItems: 0,
      isLoading: false,
      isDeleting: false,
      isSubmitting: false,
      showUserModal: false,
      userForm: {
        id: null,
        loginName: "",
        userName: "",
        sex: "1",
        identityCode: "",
        mobile: "",
      },
    };
  },
  computed: {
    // 是否有搜索条件
    hasSearchCondition() {
      return this.searchQuery || (this.queryStartDate && this.queryEndDate);
    },
    totalPages() {
      return Math.ceil(this.totalItems / this.pageSize);
    },
  },
  methods: {
    // 获取用户数据
    async fetchUserData() {
      if (this.queryStartDate && this.queryEndDate) {
        if (new Date(this.queryStartDate) > new Date(this.queryEndDate)) {
          this.$message.error("起始时间不能晚于结束时间！");
          return; // 终止请求
        }
      }
      this.isLoading = true;
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          userName: this.searchQuery || undefined, // 用户名查询条件
          startTime: this.queryStartDate || undefined, // 日期查询条件:起始时间
          endTime: this.queryEndDate || undefined, // 日期搜索条件:结束时间
        };

        // 移除undefined参数
        Object.keys(params).forEach(
          (key) => params[key] === undefined && delete params[key]
        );

        const response = await axios.get("/api/user/getAllUser", { params });

        // console.log("用户数据:", response.data);
        if (response.data.pageInfo.list == null) {
          this.$message.error("获取用户数据失败: " + response.data.msg);
          return;
        }

        this.userList = response.data.pageInfo.list || [];
        this.totalItems = response.data.pageInfo.total || 0;
      } catch (error) {
        console.error("获取用户数据失败:", error);
        this.$message.error(
          "获取用户数据失败: " + (error.response?.data?.msg || error.msg)
        );
      } finally {
        this.isLoading = false;
      }
    },

    // 重置搜索条件
    resetSearch() {
      this.searchQuery = "";
      this.queryStartDate = "";
      this.queryEndDate = "";
      this.currentPage = 1;
      this.fetchUserData();
    },

    // 修改用户回显数据
    async handleUpdate(id) {
      this.isLoading = true;
      try {
        const response = await axios.get(`/api/user/getUserById/${id}`);
        // console.log(response);
        // console.log(response.data.easyBuyUser.identityCode);
        this.userForm = {
          id: response.data.easyBuyUser.id,
          loginName: response.data.easyBuyUser.loginName,
          userName: response.data.easyBuyUser.userName,
          sex: response.data.easyBuyUser.sex.toString(),
          identityCode: response.data.easyBuyUser.identityCode,
          mobile: response.data.easyBuyUser.mobile,
        };
        this.showUserModal = true;
      } catch (error) {
        console.error("获取用户详情失败:", error);
        this.$message.error(
          "获取用户详情失败: " +
            (error.response?.data?.message || error.message)
        );
      } finally {
        this.isLoading = false;
      }
    },

    // 提交用户表单（修改）
    async submitUserForm() {
      this.isSubmitting = true;
      try {
        console.log(this.userForm);
        await axios.post(`/api/user/updateUser/`, this.userForm);

        this.$message.success("修改成功");
        this.closeUserModal();
        this.fetchUserData(); // 刷新列表
      } catch (error) {
        console.error("操作失败:", error);
        this.$message.error(
          "操作失败: " + (error.response?.data?.message || error.message)
        );
      } finally {
        this.isSubmitting = false;
      }
    },

    // 删除用户
    async handleDelete(id) {
      const confirmDelete = confirm(`确定要删除ID为 ${id} 的用户吗？`);
      if (!confirmDelete) return;

      this.isDeleting = true;
      try {
        await axios.delete(`/api/user/deleteUser/${id}`);
        this.$message.success("删除成功");
        this.fetchUserData(); // 刷新列表
      } catch (error) {
        console.error("删除失败:", error);
        this.$message.error(
          "删除失败: " + (error.response?.data?.message || error.message)
        );
      } finally {
        this.isDeleting = false;
      }
    },

    // 关闭用户表单
    closeUserModal() {
      this.showUserModal = false;
    },

    // 分页导航
    goToPrevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.fetchUserData();
      }
    },

    goToFirstPage() {
      if (this.currentPage > 1) {
        this.currentPage = 1;
        this.fetchUserData();
      }
    },

    goToNextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.fetchUserData();
      }
    },
    goToLastPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage = this.totalPages;
        this.fetchUserData();
      }
    },

    // 每页条数变化
    handlePageSizeChange() {
      this.currentPage = 1;
      this.fetchUserData();
    },

    // 性别文本转换
    getGenderText(code) {
      return code === 1 ? "男" : "女";
    },

    // 用户类型文本转换
    getUserTypeText(type) {
      return type === 0 ? "管理员" : "普通用户";
    },
  },
  created() {
      const type=sessionStorage.getItem("type");
    if(type!=0){
      this.$router.push("/");
      return;
    }
    this.fetchUserData();
  },
};
</script>

<style scoped>
.user-management-container {
  padding: 20px;
}

/* 搜索栏样式 */
.search-bar {
  display: flex;
  margin-bottom: 20px;
  padding-left: 300px;
  gap: 10px;
  align-items: center;
}

.search-bar input[type="text"] {
  flex: 1;
  max-width: 300px;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.date-input {
  padding: 7px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.search-btn,
.reset-btn {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.search-btn {
  background-color: #1890ff;
  color: white;
}

.search-btn:hover {
  background-color: #40a9ff;
}

.reset-btn {
  background-color: #f5f5f5;
  color: rgba(0, 0, 0, 0.65);
}

.reset-btn:hover {
  background-color: #e8e8e8;
}

.user-table-container {
  width: 70%;
  min-width: 1000px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 表格样式 */
.table-header {
  display: flex;
  background-color: #fafafa;
  font-weight: bold;
  border-bottom: 1px solid #e8e8e8;
}

.table-row {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
}

.table-row:hover {
  background-color: #fafafa;
}

.table-cell {
  padding: 16px;
  flex: 1;
  min-width: 0;
  word-wrap: break-word;
}

.id-column {
  flex: 0 0 80px;
}

.name-column,
.realname-column {
  flex: 1;
}

.gender-column,
.type-column {
  flex: 0 0 100px;
}

.time-column {
  flex: 0 0 150px;
}

.action-column {
  flex: 0 0 180px;
  display: flex;
  gap: 10px;
}

.update-btn,
.delete-btn {
  padding: 4px 8px;
  border: none;
  border-radius: 2px;
  cursor: pointer;
}

.update-btn {
  background-color: #1890ff;
  color: white;
}

.update-btn:hover {
  background-color: #40a9ff;
}

.delete-btn {
  background-color: #ff4d4f;
  color: white;
}

.delete-btn:hover {
  background-color: #ff7875;
}

.delete-btn:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  gap: 15px;
}

.page-btn {
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
}

.page-btn:hover:not(:disabled) {
  color: #1890ff;
  border-color: #1890ff;
}

.page-btn:disabled {
  color: rgba(0, 0, 0, 0.25);
  cursor: not-allowed;
}

.page-size-select {
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.user-modal {
  background-color: white;
  border-radius: 4px;
  width: 500px;
  max-width: 90%;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: rgba(0, 0, 0, 0.45);
}

.modal-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 70%;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.radio-group {
  display: flex;
  gap: 16px;
}

.radio-group label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: normal;
  cursor: pointer;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 24px;
}

.cancel-btn,
.submit-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  background-color: #fff;
  border: 1px solid #d9d9d9;
}

.cancel-btn:hover {
  color: #1890ff;
  border-color: #1890ff;
}

.submit-btn {
  background-color: #1890ff;
  color: white;
  border: none;
}

.submit-btn:hover {
  background-color: #40a9ff;
}

.submit-btn:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

/* 图标样式 */
.icon-search::before {
  content: "🔍";
}

.loading-state,
.empty-state {
  text-align: center;
  padding: 40px;
  color: #999;
}
</style>